<template>
  <div class="community-page">
    <!-- 导航栏 -->
    <van-nav-bar title="Community" fixed placeholder>
      <template #right>
        <van-icon name="plus" size="18" @click="createPost" />
      </template>
    </van-nav-bar>

    <!-- 内容筛选组件 -->
    <ContentFilter @filter-change="handleFilterChange" @search="handleSearch" @tab-change="handleTabChange" />

    <!-- 内容列表 -->
    <div class="content-list">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-section">
        <van-loading size="24px" vertical>Loading content...</van-loading>
      </div>

      <!-- 内容项 -->
      <div v-else-if="contentItems.length > 0" class="content-items">
        <template v-for="item in contentItems" :key="`${item.type}-${item.id}`">
          <!-- 分享卡片 -->
          <ShareCard v-if="item.type === 'share'" :share="item.data" @click="viewShareDetail" @like="toggleShareLike"
            @bookmark="toggleShareBookmark" @comment="viewShareComments" @share="shareContent" />

          <!-- 求助卡片 -->
          <HelpRequestCard v-else-if="item.type === 'help'" :help-request="item.data" @click="viewHelpDetail"
            @answer="answerHelpRequest" @bookmark="toggleHelpBookmark" />
        </template>
      </div>

      <!-- 空状态 -->
      <van-empty v-else description="No content found" image="search">
        <van-button type="primary" @click="clearFilters">
          Clear Filters
        </van-button>
      </van-empty>
    </div>

    <!-- 加载更多 -->
    <div class="load-more" v-if="hasMore && !loading">
      <van-button :loading="loadingMore" @click="loadMore" block type="primary" plain>
        Load More
      </van-button>
    </div>

    <!-- 发布按钮 -->
    <div class="floating-action">
      <van-button type="primary" size="large" round icon="plus" @click="createPost" class="fab">
        Post
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { communityApi, type CommunityShare } from '@/api'
import type { HelpRequest } from '@/api/community'
import ContentFilter from '@/components/ContentFilter.vue'
import ShareCard from '@/components/ShareCard.vue'
import HelpRequestCard from '@/components/HelpRequestCard.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const loadingMore = ref(false)
const shares = ref<CommunityShare[]>([])
const helpRequests = ref<HelpRequest[]>([])
const currentTab = ref('all')
const currentFilters = ref({
  share_type: undefined as string | undefined,
  status: undefined as string | undefined,
  category: undefined as string | undefined
})
const searchQuery = ref('')
const hasMore = ref(true)
const currentPage = ref(1)

// 计算属性
const contentItems = computed(() => {
  const items: Array<{ type: string; id: number; data: any; timestamp: string }> = []

  // 添加分享内容
  shares.value.forEach(share => {
    items.push({
      type: 'share',
      id: share.id,
      data: share,
      timestamp: share.created_at || new Date().toISOString()
    })
  })

  // 添加求助内容
  helpRequests.value.forEach(help => {
    items.push({
      type: 'help',
      id: help.id,
      data: help,
      timestamp: help.created_at || new Date().toISOString()
    })
  })

  // 按时间排序
  return items.sort((a, b) =>
    new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
  )
})

// 方法
const loadContent = async (reset = false) => {
  try {
    if (reset) {
      loading.value = true
      currentPage.value = 1
      shares.value = []
      helpRequests.value = []
    } else {
      loadingMore.value = true
    }

    // 根据标签加载不同类型的内容
    if (currentTab.value === 'all' || currentTab.value === 'shares') {
      // 只传递API支持的参数
      const sharesParams = {
        page: currentPage.value,
        share_type: currentFilters.value.share_type
      }
      const sharesResponse = await communityApi.getShares(sharesParams)
      let sharesData: CommunityShare[] = []

      if (Array.isArray(sharesResponse)) {
        sharesData = sharesResponse
      } else if (sharesResponse && 'data' in sharesResponse && Array.isArray(sharesResponse.data)) {
        sharesData = sharesResponse.data
      }

      if (reset) {
        shares.value = sharesData
      } else {
        shares.value.push(...sharesData)
      }
    }

    if (currentTab.value === 'all' || currentTab.value === 'help') {
      // 只传递API支持的参数
      const helpParams = {
        status: currentFilters.value.status,
        category: currentFilters.value.category
      }
      const helpResponse = await communityApi.getHelpRequests(helpParams)
      let helpData: HelpRequest[] = []

      if (Array.isArray(helpResponse)) {
        helpData = helpResponse
      } else if (helpResponse && 'data' in helpResponse && Array.isArray(helpResponse.data)) {
        helpData = helpResponse.data
      }

      if (reset) {
        helpRequests.value = helpData
      } else {
        helpRequests.value.push(...helpData)
      }
    }

    // 检查是否还有更多内容
    hasMore.value = (shares.value.length + helpRequests.value.length) % 20 === 0

  } catch (error) {
    console.error('Failed to load content:', error)
    showToast('Failed to load content')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const loadMore = async () => {
  currentPage.value++
  await loadContent(false)
}

const handleTabChange = (tab: string) => {
  currentTab.value = tab
  loadContent(true)
}

const handleFilterChange = (filters: any) => {
  currentFilters.value = filters
  loadContent(true)
}

const handleSearch = (query: string) => {
  searchQuery.value = query
  loadContent(true)
}

const clearFilters = () => {
  currentFilters.value = {}
  searchQuery.value = ''
  currentTab.value = 'all'
  loadContent(true)
}

// 分享相关操作
const viewShareDetail = (share: CommunityShare) => {
  router.push(`/community/share/${share.id}`)
}

const toggleShareLike = async (share: CommunityShare) => {
  try {
    await communityApi.interactWithShare(share.id, {
      interaction_type: 'like'
    })

    share.is_liked = !share.is_liked
    if (share.likes_count !== undefined) {
      share.likes_count += share.is_liked ? 1 : -1
    }

    showToast(share.is_liked ? 'Liked!' : 'Unliked!')
  } catch (error) {
    console.error('Failed to toggle like:', error)
    showToast('Failed to update like')
  }
}

const toggleShareBookmark = async (share: CommunityShare) => {
  try {
    // TODO: 实现书签API
    share.is_bookmarked = !share.is_bookmarked
    showToast(share.is_bookmarked ? 'Bookmarked!' : 'Removed from bookmarks!')
  } catch (error) {
    console.error('Failed to toggle bookmark:', error)
    showToast('Failed to update bookmark')
  }
}

const viewShareComments = (share: CommunityShare) => {
  router.push(`/community/share/${share.id}#comments`)
}

const shareContent = async () => {
  try {
    const shareData = {
      title: 'Social Dojo Community',
      text: 'Join me on Social Dojo to improve your social skills!',
      url: window.location.origin
    }

    if (navigator.share) {
      await navigator.share(shareData)
      showToast('Shared successfully!')
    } else {
      // Fallback for browsers that don't support Web Share API
      await navigator.clipboard.writeText(shareData.url)
      showToast('Link copied to clipboard!')
    }
  } catch (error) {
    if (error instanceof Error && error.name !== 'AbortError') {
      showToast('Failed to share content')
    }
  }
}

// 求助相关操作
const viewHelpDetail = (helpRequest: any) => {
  router.push(`/community/help/${helpRequest.id}`)
}

const answerHelpRequest = (helpRequest: any) => {
  router.push(`/community/help/${helpRequest.id}/answer`)
}

const toggleHelpBookmark = async (helpRequest: any) => {
  try {
    // TODO: 实现书签API
    helpRequest.is_bookmarked = !helpRequest.is_bookmarked
    showToast(helpRequest.is_bookmarked ? 'Bookmarked!' : 'Removed from bookmarks!')
  } catch (error) {
    console.error('Failed to toggle bookmark:', error)
    showToast('Failed to update bookmark')
  }
}

const createPost = () => {
  router.push('/community/publish')
}

// 生命周期
onMounted(() => {
  loadContent(true)
})
</script>

<style lang="scss" scoped>
.community-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 80px;

  .content-list {
    padding: 16px;

    .loading-section {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
    }

    .content-items {
      display: flex;
      flex-direction: column;
      gap: 0; // ShareCard 和 HelpRequestCard 已经有自己的 margin-bottom
    }
  }

  .load-more {
    padding: 16px;
  }

  .floating-action {
    position: fixed;
    bottom: 80px;
    right: 20px;
    z-index: 100;

    .fab {
      width: 56px;
      height: 56px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

      :deep(.van-button__text) {
        display: none;
      }

      :deep(.van-icon) {
        font-size: 24px;
      }
    }
  }
}
</style>